class Photo < Asset
  
  attr_accessor :crop_x, :crop_y, :crop_w, :crop_h

  after_update  :reprocess_photo, :if => :cropping?

  has_attached_file :attachment,

    :styles => {
        #Product detail (not main photo)
        :small_thumb => {
          :geometry => Setting.get("photo_small_thumb_size"),
          :processors => [:auto_orient, :cropper],
          :quality => 40,
          :format => 'JPG'
        },

        #Admin photo overview, Products overview
        :thumb => {
          :geometry => Setting.get("photo_thumb_size"),
          :processors => [:auto_orient, :cropper],#, :watermark
          :watermark_path => Setting.get("photo_small_watermark_path"),
          :position => Setting.get("photo_thumb_watermark_position"),
          :quality => 50,
          :format => 'JPG'
        },

        #Product detail (main photo)
        :small => {
          :geometry => Setting.get("photo_small_size"),
          :processors => [:auto_orient, :cropper],#, :watermark
          :watermark_path => Setting.get("photo_small_watermark_path"),
          :position => Setting.get("photo_small_watermark_position"),
          :quality => 60,
          :format => 'JPG'
        },

        #Photo detail
        :large => {
          :geometry => Setting.get("photo_large_size"),
          :processors => [:auto_orient, :cropper],#, :watermark
          :watermark_path => Setting.get("photo_watermark_path"),
          :position => Setting.get("photo_large_watermark_position"),
          :quality => 70,
          :format => 'JPG'
        },

        #Admin photo for cropping
        :large_not_cropped => {
          :geometry => "850x800>",
          :quality => 100,
          :format => 'JPG'
        },
     },

    :default_style => :large
  
  validates :description, :length => {:maximum => 250}, :allow_blank => true
  validates :attachment_file_name, :presence => true if lambda {|attr| attr.object.new_record?}
  validates_attachment_content_type :attachment, :content_type => ['image/jpeg', 'image/gif', 'image/x-png', 'image/png']
  validate :attachment_check

  def photo_geometry(style = :original)
    @geometry ||= {}
    @geometry[style] ||= Paperclip::Geometry.from_file(attachment.path(style))
  end

  def attachment_check
    unless attachment.errors.empty?
      errors.add(:base, "Při upravování fotky ('#{attachment_file_name}') došlo k chybě. Zkontrolujte ImageMagick, nebo zdrojový soubor.")
      false
    end
  end
  
  def cropping?
    !crop_w.blank? && !crop_h.blank?
  end

  private
  def reprocess_photo
    attachment.reprocess!
  end
end
